#!/usr/local/bin/python
# -*- coding: utf-8 -*-

#################################################
# 模块功能：用于解析新的支付宝账号信息
##################################################
import xlrd2 as xlrd

import initAlipayPage
from data_alchemy.alipay_bill_new_alchemy import AlipayBillNewAlchemy
from datetime import datetime

from initLogger import logger


class ParseAlipayNew:

    def __init__(self):
        '''
        函数功能：构造函数
        '''

        self.billParseRules = None  #账单解析规则
        self.alipayBillInforList = None #支付宝账单信息列表
        self.tradeTimeFirst =None
        self.tradeCreateTimeOther = None
        self.tradePaymentTimeOther = None
        self.tradeLastModifiedTimeOther = None
        self.typeOther = None #当前订单的类型
        self.curYear=0    #当前支付宝账单的所属年份
        self.curMonth=0   #当前支付宝账单的所属月份
        self.tradeStatusFirst=None  #交易状态
        self.tradeStatusOther=None  #交易状态


    def loadAlipayBill(self, filePath):
        '''
        函数功能：导入整合后的支付宝账单
        :param filePath:
        :param year:  暂时考虑不用时间参数
        :param month:
        :return:
        '''

        workbook = xlrd.open_workbook(filePath)
        table = workbook.sheet_by_index(0)

        for index in range(table.nrows):
            alipayBillItemRowList = table.row_values(rowx=index, start_colx=0, end_colx=None)

            if index==0:
                #excel表的第一行（标题行）跳过

                continue

            if len(alipayBillItemRowList) < initAlipayPage.NEW_ALIPAY_BILL_COLUMN_COUNT - 2:
                logger.debug("账单数据异常：%s" % str(alipayBillItemRowList))
                continue


            logger.debug("bill infor:%s"%str(alipayBillItemRowList))

            #if type(alipayBillItemRowList[14])=="str":

            #处理账单的时间信息
            self.DealAlipayBillCurTimeinfor(workbook, alipayBillItemRowList)

            tradeOrderIdFirst = alipayBillItemRowList[9].rstrip()

            #判断当前订单是否存在
            isBillExist = self.IsAlipayBillItemExist(tradeOrderIdFirst)

            if (isBillExist==True):
                #账单已经存在，对账上进行更新
                logger.debug("in loadAlipayBill function: call UpdateAlipayBillItem")
                self.UpdateAlipayBillItem(tradeOrderIdFirst, alipayBillItemRowList)
            else:
                #账单不存在，添加新的账单
                logger.debug("in loadAlipayBill function: call AddAlipayBillItem")
                self.AddAlipayBillItem(alipayBillItemRowList)



        #for index in range(table.nrows):

    def DealAlipayBillCurTimeinfor(self, xlrdWorkbook, alipayBillItemRowList):
        '''
        函数功能：处理账单中时间转化事项
        :param alipayBillItemRowList:
        :return:
        '''


        if isinstance(alipayBillItemRowList[0], float):
            self.tradeTimeFirst  = xlrd.xldate_as_datetime(alipayBillItemRowList[0], xlrdWorkbook.datemode)
        else:
            self.tradeTimeFirst  = None

        if isinstance(alipayBillItemRowList[14], float):
            self.tradeCreateTimeOther = xlrd.xldate_as_datetime(alipayBillItemRowList[14], xlrdWorkbook.datemode)
        else:
            self.tradeCreateTimeOther = None

        if isinstance(alipayBillItemRowList[15], float):
            self.tradePaymentTimeOther = xlrd.xldate_as_datetime(alipayBillItemRowList[15], xlrdWorkbook.datemode)
        else:
            self.tradePaymentTimeOther = None

        if isinstance(alipayBillItemRowList[16], float):
            self.tradeLastModifiedTimeOther = xlrd.xldate_as_datetime(alipayBillItemRowList[16], xlrdWorkbook.datemode)
        else:
            self.tradeLastModifiedTimeOther = None

        self.typeOther = alipayBillItemRowList[18]
        self.tradeStatusFirst = alipayBillItemRowList[8]
        self.tradeStatusOther = alipayBillItemRowList[23]

        if (self.tradeLastModifiedTimeOther==None):
            #如果最后修改时间不为None，按照最后修改时间进行记录
            self.curYear = self.tradeLastModifiedTimeOther.year
            self.curMonth = self.tradeLastModifiedTimeOther.month
        else:
            # 如果最后修改时间为None，按照创建时间进行记录
            self.curYear = self.tradeLastModifiedTimeOther.year
            self.curMonth  = self.tradeLastModifiedTimeOther.month






    def IsAlipayBillItemExist(self, tradeOrderId):
            '''
            函数功能：判断当前账单是否已经存在
            :return: boolean
                存在反馈Ture
                不存在反馈False
            '''
            alipayBillNewAlchemy = AlipayBillNewAlchemy()
            alipayBillItemList = alipayBillNewAlchemy.SearchAlipayBillByTradeOrderId(tradeOrderId)

            if (len(alipayBillItemList)>0):
                return True
            else:
                return False

            pass

    def UpdateAlipayBillItem(self, tradeOrderId, alipayBillItemRowList):
        '''
        函数功能：对已存在的支付宝账单信息进行更新
        :param alipayBillItemRowList:
        :return:
        '''
        alipayBillNewAlchemy = AlipayBillNewAlchemy()


        alipayBillNewAlchemy.UpdateAlipayBillItemByTradeOrderId(tradeOrderId,
                                                                self.tradeStatusFirst,
                                                                self.tradeStatusOther,
                                                                self.typeOther,
                                                                self.tradePaymentTimeOther,
                                                                self.tradeLastModifiedTimeOther)



    def AddAlipayBillItem(self, alipayBillItemRowList):
        '''
        函数功能：添加一条新的支付宝账单记录
        :param alipayBillItemRowList:
        :return:
        '''



        alipayBillNewAlchemy = AlipayBillNewAlchemy(    tradeTimeFirst=self.tradeTimeFirst,
                                                        tradeTypeFirst=alipayBillItemRowList[1].rstrip(),
                                                        tradeObjectFirst=alipayBillItemRowList[2].rstrip(),
                                                        tradeAccountFirst=alipayBillItemRowList[3].rstrip(),
                                                        commodityDescriptionFirst=str(alipayBillItemRowList[4]).rstrip(),
                                                        incomeExpensesFirst=alipayBillItemRowList[5].rstrip(),
                                                        valueFirst=alipayBillItemRowList[6],
                                                        receiptPayTypeFirst=alipayBillItemRowList[7].rstrip(),
                                                        tradeStatusFirst=alipayBillItemRowList[8].rstrip(),
                                                        tradeOrderNoFirst=alipayBillItemRowList[9].rstrip(),
                                                        businessOrderNoFirst=alipayBillItemRowList[10].rstrip(),
                                                        remarkFirst=alipayBillItemRowList[11].rstrip(),
                                                        tradeOrderNoOther=alipayBillItemRowList[12].rstrip(),
                                                        businessOrderNoOther=alipayBillItemRowList[13].rstrip(),
                                                        tradeCreateTimeOther=self.tradeCreateTimeOther,
                                                        tradePaymentTimeOther=self.tradePaymentTimeOther,
                                                        tradeLastModifiedTimeOther=self.tradeLastModifiedTimeOther,
                                                        tradeSourceOther=alipayBillItemRowList[17].rstrip(),
                                                        typeOther=alipayBillItemRowList[18].rstrip(),
                                                        tradeObjectOther=alipayBillItemRowList[19].rstrip(),
                                                        commodityNameOther=str(alipayBillItemRowList[20]).rstrip(),
                                                        valueOther=alipayBillItemRowList[21],
                                                        incomeExpensesOther=alipayBillItemRowList[22].rstrip(),
                                                        tradeStatusOther=alipayBillItemRowList[23].rstrip(),
                                                        valueServiceChargeOther=alipayBillItemRowList[24],
                                                        valueRefundOther=alipayBillItemRowList[25],
                                                        remarkOther=str(alipayBillItemRowList[26]).rstrip(),
                                                        fundStatusOther=alipayBillItemRowList[27].rstrip(),
                                                        billType="billType",
                                                        matched=False
                                                        )

        alipayBillNewAlchemy.AddAlipayBillItem()
